package com.situ.hospital.user.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.hospital.user.model.UserModel;
import com.situ.hospital.user.service.UserService;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

//		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		switch (action) {
		case "register":
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			if (username == "" || username == null) {
				response.getWriter().write("请输入姓名");
			} else if (password == "" || password == null) {
				response.getWriter().write("请输入密码");
			} else {
				UserModel user = new UserModel(username, password);
				UserService us = new UserService();
//				System.out.println(username);
				try {
//					System.out.println("1");
					response.getWriter().write(String.valueOf(us.insert(user)));
//					response.getWriter().write(String.valueOf(us.login(user)));
				} catch (IOException | SQLException e) {
					e.printStackTrace();
				}
			}
			break;

		case "login":
			String username2 = request.getParameter("username");
			String password2 = request.getParameter("password");
			if (username2 == "" || username2 == null) {
				response.getWriter().write("请输入姓名");
			} else if (password2 == "" || password2 == null) {
				response.getWriter().write("请输入密码");
			} else {
//				System.out.println(username2);
				UserModel user = new UserModel(username2, password2);
				UserService us = new UserService();
				try {
					request.getSession().setAttribute("username", username2);
					response.getWriter().write(String.valueOf(us.login(user)));
				} catch (SQLException e) {
					e.printStackTrace();
				}

			}
			break;
		}
	}

}
